package com.xls.commonlibrary.wx;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.hjq.toast.Toaster;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.SubscribeMessage;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelbiz.WXOpenBusinessView;
import com.tencent.mm.opensdk.modelbiz.WXOpenBusinessWebview;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.opensdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mmkv.MMKV;
import com.xls.commonlibrary.http.Api;
import com.xls.commonlibrary.http.GetUtil;
import com.xls.commonlibrary.http.Transformer;
import com.xls.commonlibrary.http.box.SPUtils;
import com.xls.commonlibrary.util.ListStringUtil;
import com.xls.commonlibrary.util.eventbus.MessageEvent;
import com.xls.commonlibrary.wxapi.NetworkUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;

import static com.xls.commonlibrary.constant.BroadAction.ACTION_BR_WEIXIN_LOGIN;
import static com.xls.commonlibrary.util.eventbus.ConstEventBus.EVENT_LOGIN_DISSMISS_DIALOG;
import static com.xls.commonlibrary.util.eventbus.ConstEventBus.EVENT_TIXIAN_SHOWQUAN_OK;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_ACCESS_TOKEN;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_CITY;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_COUNTRY;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_EXPIRES_IN;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_HEADIMGURL;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_NICKNAME;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_OPEN_ID;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_PRIVILEGE;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_PROVINCE;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_REFRESH_TOKEN;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_SCOPE;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_SEX;
import static com.xls.commonlibrary.wxapi.ConstWx.KEY_WX_UNION_ID;
import static com.xls.commonlibrary.wxapi.ConstWx.wxAppId;
import static com.xls.commonlibrary.wxapi.ConstWx.wxAppSecret;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private static String TAG = "WXEntryActivity";

    static MMKV kv = MMKV.mmkvWithID("InterProcessKV", MMKV.MULTI_PROCESS_MODE);
    private IWXAPI api;
    private MyHandler handler;

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    private static class MyHandler extends Handler {
        private final WeakReference<WXEntryActivity> wxEntryActivityWeakReference;

        public MyHandler(WXEntryActivity wxEntryActivity) {
            wxEntryActivityWeakReference = new WeakReference<WXEntryActivity>(wxEntryActivity);
        }


        @SuppressLint("CheckResult")
        @Override
        public void handleMessage(Message msg) {
            int tag = msg.what;
            switch (tag) {
                case NetworkUtil.GET_TOKEN: {// 获取token成功，可以获取各种信息
                    Bundle data = msg.getData();
                    JSONObject json = null;
                    try {
                        json = new JSONObject(data.getString("result"));


                        String openId, accessToken, refreshToken, scope, unionid;
                        int expires_in = 0;

                        // openid here
                        openId = json.getString("openid");
                        unionid = json.getString("unionid");
                        accessToken = json.getString("access_token");
                        refreshToken = json.getString("refresh_token");
                        scope = json.getString("scope");
                        expires_in = json.getInt("expires_in");

                        Log.d(TAG, "GET_TOKEN openId: " + openId);
                        Log.d(TAG, "GET_TOKEN unionid: " + unionid);

                        // cache by mmkv
                        kv.encode(KEY_WX_OPEN_ID, openId);
                        kv.encode(KEY_WX_UNION_ID, unionid);
                        kv.encode(KEY_WX_ACCESS_TOKEN, accessToken);
                        kv.encode(KEY_WX_REFRESH_TOKEN, refreshToken);
                        kv.encode(KEY_WX_SCOPE, scope);
                        kv.encode(KEY_WX_EXPIRES_IN, expires_in + "");

                        // send by enventbus

//                        EventBus.getDefault().post(new MessageEvent(EVENT_WX_INFO_GET_SUCCESS, "success"));

                        // todo 增加1步操作： 获取 微信信息后再通知主页去登陆

                        GetUtil.getInstance().create(Api.class)
                                .getWxUserInfo(accessToken, openId, "zh_CN")
                                .compose(Transformer.transform())
                                .subscribe(info -> {

                                    Logger.d("=======getWxUserInfo========");
                                    Logger.d(info);
//                                           {openid='okLNi6cnp3emUBwnXXWuBnpbNQ5k',
//                                            nickname='菊花台',
//                                            sex=0,
//                                            province='',
//                                            city='', country='',
//                                            headimgurl='https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83epbhgnqJJcWRZSDLtkMEF1YxicPtMmBtKDw7EBg6Fick58JXGlQEcrsILzmiauC3zYOfiaCIIQv2v6iaWA/132',
//                                            privilege=[],
//                                            unionid='oScND6eIN-kwxcJftDLvoIkBYB_w'}

                                    // save info mmkv
                                    kv.encode(KEY_WX_HEADIMGURL, info.getHeadimgurl());
                                    kv.encode(KEY_WX_NICKNAME, info.getNickname());
                                    kv.encode(KEY_WX_SEX, info.getSex());
                                    kv.encode(KEY_WX_PROVINCE, info.getProvince());
                                    kv.encode(KEY_WX_CITY, info.getCity());
                                    kv.encode(KEY_WX_COUNTRY, info.getCountry());
                                    // 注意这里是个数组
                                    if (info.getPrivilege() != null && info.getPrivilege().size() > 0) {
                                        kv.encode(KEY_WX_PRIVILEGE, ListStringUtil.list2String(info.getPrivilege()));
                                    }


                                    // send br
                                    Intent intent = new Intent();
                                    //对应BroadcastReceiver中intentFilter的action
                                    intent.setAction(ACTION_BR_WEIXIN_LOGIN);
                                    //发送广播
                                    LocalBroadcastManager.getInstance(wxEntryActivityWeakReference.get()).sendBroadcast(intent);

                                }, throwable -> {

                                    // 失败了
                                    Toaster.show(throwable);

                                });


//                        Intent intent = new Intent(wxEntryActivityWeakReference.get(), SendToWXActivity.class);
//                        intent.putExtra("openId", openId);
//                        intent.putExtra("accessToken", accessToken);
//                        intent.putExtra("refreshToken", refreshToken);
//                        intent.putExtra("scope", scope);
//                        wxEntryActivityWeakReference.get().startActivity(intent);

                    } catch (JSONException e) {
                        Log.e(TAG, e.getMessage());
                    }
                }
            }
        }
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Toaster.show("wx act on create");
        Logger.d("=============Wechat===WXEntryActivity==========");

        api = WXAPIFactory.createWXAPI(this, wxAppId, false);
        //api = WXAPIFactory.createWXAPI(this, "102410231", false);
        handler = new MyHandler(this);

        try {
            Intent intent = getIntent();
            api.handleIntent(intent, this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Logger.d("=======wx act onNewIntent========");
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
        switch (req.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                goToGetMsg();
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                goToShowMsg((ShowMessageFromWX.Req) req);
                break;
            default:
                break;
        }
        finish();
    }


    @Override
    public void onResp(BaseResp resp) {


        Logger.d("===========================weixin onResp=======================");
        Logger.d(resp.errCode);
        Logger.d(resp.errStr);

        int result = 0;

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
//                result = R.string.errcode_success;
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
//                result = R.string.errcode_cancel;
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
//                result = R.string.errcode_deny;
                break;
            case BaseResp.ErrCode.ERR_UNSUPPORT:
//                result = R.string.errcode_unsupported;
                break;
            default:
//                result = R.string.errcode_unknown;
                break;
        }

        //Toaster.show("wexin授权:  errCode"+resp.errCode + ", type=" + resp.getType());


        if (resp.getType() == ConstantsAPI.COMMAND_SUBSCRIBE_MESSAGE) {
            SubscribeMessage.Resp subscribeMsgResp = (SubscribeMessage.Resp) resp;
//            String text = String.format("openid=%s\ntemplate_id=%s\nscene=%d\naction=%s\nreserved=%s",
//                    subscribeMsgResp.openId, subscribeMsgResp.templateID, subscribeMsgResp.scene, subscribeMsgResp.action, subscribeMsgResp.reserved);
//
//            Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        }

        if (resp.getType() == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM) {
            WXLaunchMiniProgram.Resp launchMiniProgramResp = (WXLaunchMiniProgram.Resp) resp;
            EventBus.getDefault().post(new MessageEvent(EVENT_TIXIAN_SHOWQUAN_OK, ""));
//            String text = String.format("openid=%s\nextMsg=%s\nerrStr=%s",
//                    launchMiniProgramResp.openId, launchMiniProgramResp.extMsg, launchMiniProgramResp.errStr);
//
//            Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        }

        if (resp.getType() == ConstantsAPI.COMMAND_OPEN_BUSINESS_VIEW) {
            WXOpenBusinessView.Resp launchMiniProgramResp = (WXOpenBusinessView.Resp) resp;
//            String text = String.format("openid=%s\nextMsg=%s\nerrStr=%s\nbusinessType=%s",
//                    launchMiniProgramResp.openId, launchMiniProgramResp.extMsg, launchMiniProgramResp.errStr, launchMiniProgramResp.businessType);
//
//            Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        }

        if (resp.getType() == ConstantsAPI.COMMAND_OPEN_BUSINESS_WEBVIEW) {
            WXOpenBusinessWebview.Resp response = (WXOpenBusinessWebview.Resp) resp;
//            String text = String.format("businessType=%d\nresultInfo=%s\nret=%d", response.businessType, response.resultInfo, response.errCode);
//
//            Toast.makeText(this, text, Toast.LENGTH_LONG).show();
        }

        // 微信登陆
        if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
            if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
                Logger.d("===========================weixin onResp=======授权成功================");
                // 授权成功
                SendAuth.Resp authResp = (SendAuth.Resp) resp;
                final String code = authResp.code;
                // get token
//            NetworkUtil.sendWxAPI(handler,
//                    String.format("https://api.weixin.qq.com/sns/oauth2/access_token?" +
//                                    "appid=%s&secret=%s&code=%s&grant_type=authorization_code", "wxd930ea5d5a258f4f",
//                            "1d6d1d57a3dd063b36d917bc0b44d964", code),
//                    NetworkUtil.GET_TOKEN);


                NetworkUtil.sendWxAPI(handler,
                        String.format(
                                "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                                        "appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                                wxAppId,
                                wxAppSecret,
                                code),
                        NetworkUtil.GET_TOKEN);
            } else {
                Logger.d("===========================weixin onResp=======授权失败================");
//                授权失败  销毁登录页dialog
                EventBus.getDefault().post(new MessageEvent(EVENT_LOGIN_DISSMISS_DIALOG, ""));
            }
        }
        finish();
    }

    private void goToGetMsg() {
//		Intent intent = new Intent(this, GetFromWXActivity.class);
//		intent.putExtras(getIntent());
//		startActivity(intent);
//		finish();
    }

    private void goToShowMsg(ShowMessageFromWX.Req showReq) {
        WXMediaMessage wxMsg = showReq.message;
        WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;

        StringBuffer msg = new StringBuffer();
        msg.append("description: ");
        msg.append(wxMsg.description);
        msg.append("\n");
        msg.append("extInfo: ");
        msg.append(obj.extInfo);
        msg.append("\n");
        msg.append("filePath: ");
        msg.append(obj.filePath);

//		Intent intent = new Intent(this, ShowFromWXActivity.class);
//		intent.putExtra(Constants.ShowMsgActivity.STitle, wxMsg.title);
//		intent.putExtra(Constants.ShowMsgActivity.SMessage, msg.toString());
//		intent.putExtra(Constants.ShowMsgActivity.BAThumbData, wxMsg.thumbData);
//		startActivity(intent);
        finish();
    }
}